﻿using Exam.infranstuctrue.Dto.other;
using Exam.infranstuctrue.Dto.Request.Exam;
using Exam.infranstuctrue.Dto.Request.Exercise;
using Exam.infranstuctrue.Dto.Respones;
using Exam.infranstuctrue.Dto.Respones.Exam;
using Exam.infranstuctrue.Dto.Respones.Exercis;
using Exam.infranstuctrue.Dto.Respones.Simulation;
using Exam.infranstuctrue.Dto.Respones.Task;
using Exam.infranstuctrue.EFCore;
using Exam.infranstuctrue.IOC;
using Exam.infranstuctrue.Tools;
using Exam.infranstuctrue.Tools.Attributes;
using Exam.Infrastrucrure.Dto;
using Exam.Service.Interface;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;

namespace Exam.Service.Instance
{
    [Iinjection]
    public class ExercisServer : BaseService, IExerciseServer
    {
        private readonly ExamIOC _examIOC;
        private readonly ExerciseIOC _exerciseIOC;

        public ExercisServer(ExamIOC examIOC, ExerciseIOC exerciseIOC)
        {
            _examIOC = examIOC;
            _exerciseIOC = exerciseIOC;
        }
        /// <summary>
        /// 获取用户
        /// </summary>
        /// <param name="orgabizationuids"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        private string GetUser(string orgabizationuids, string? token = null)
        {
            var uname = "";
            var url = "https://change.qiudaoyu.top/api/Admin/GetUser/?page=1&&limit=99999";
            var users = Http.Get(url, token);
            var user = JsonConvert.DeserializeObject<MyApiResult>(users);
            var userchilren = JsonConvert.SerializeObject(user.data);
            var result = JsonConvert.DeserializeObject<MyApiResultChliren>(userchilren);
            var res = JsonConvert.SerializeObject(result.data);
            var data = JsonConvert.DeserializeObject<List<ResponseAdminDto>>(res);

            var uids = data.Select(d => d.id).ToList();
            if (!string.IsNullOrEmpty(orgabizationuids))
            {

                var uid = orgabizationuids.Split(",");
                uname = "";
                foreach (var item2 in uid)
                {
                    var iq = data.Where(d => d.id == item2).Single();
                    uname += iq.name + ",";
                }
                uname = uname.Substring(0, uname.Length - 1);
            }
            return uname;
        }
        /// <summary>
        /// 随机数
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        private List<int>? Random(int count)
        {
            List<int> newList = new List<int>();
            for (int i = 0; i < count; i++)
            {
                newList.Add(i + 1);
            }
            //打乱
            for (int i = 0; i < count; i++)
            {
                int y;
                Random rd = new Random();
                var num1 = rd.Next(1, count);
                do
                {
                    y = rd.Next(0, count);
                } while (y == num1);
                var num2 = newList[num1];
                newList[num1] = newList[y];
                newList[y] = num2;
            }
            return newList;
        }
        /// <summary>
        /// 开始刷题
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult> GetQuestionBank(string? uid)
        {
            var exe = await _exerciseIOC._examExerciseEFCore.QueryAll(d => d.Euid == uid).FirstOrDefaultAsync();
            if (exe == null)
            {
                ExamExercise examExercise = new ExamExercise();
                examExercise.Eid = Config.GUID();
                examExercise.Euid = uid;
                examExercise.Edesc = "";
                examExercise.Etimestamp = 0;
                examExercise.Ecount = 0;
                examExercise.EcreateTime = DateTime.Now;
                examExercise.ErightCount = 0;
                _exerciseIOC._examExerciseEFCore.Add(examExercise);
                _exerciseIOC._examExerciseEFCore.SaveChanges();
            }
            var taskdetali = await _exerciseIOC._examTaskDetailEFCore.QueryAll(d => d.Tduid.Contains(uid)).ToListAsync();
            var tasks = await _exerciseIOC._examTaskEFCore.QueryAll(d => 1 == 1).ToListAsync();
            foreach (var item in taskdetali)
            {
                var task = tasks.Where(d => d.Tid == item.Tdtid).FirstOrDefault();
                if (task.TbeginTime < DateTime.Now && task.TendTime > DateTime.Now)
                {
                    if (item.TdbeginTime == null)
                    {
                        item.TdbeginTime = DateTime.Now;
                    }
                }
            }
            _exerciseIOC._examTaskDetailEFCore.UpdateRange(taskdetali);
            _exerciseIOC._examTaskDetailEFCore.SaveChanges();

            var questionbankdetali = await _examIOC._examQuestionBankDetaliEFCore.QueryAll(d => 1 == 1).ToListAsync();
            var newlist = Random(questionbankdetali.Count());
            var questions = await _examIOC._examQuestionEFCore.QueryAll(d => 1 == 1).ToListAsync();
            var options = await _examIOC._examoptionEFCore.QueryAll(d => 1 == 1).ToListAsync();
            List<QuestionRes> questionRes = new List<QuestionRes>();
            for (int i = 0; i < newlist.Count(); i++)
            {
                var question = questions.Where(d => d.Qid == questionbankdetali[newlist[i] - 1].Qbqid).Single();
                var option = options.Where(d => d.Oqid == questionbankdetali[newlist[i] - 1].Qbqid).ToList();
                List<OptionRes> optionRes = new List<OptionRes>();
                foreach (var item2 in option)
                {
                    optionRes.Add(new OptionRes
                    {
                        Oid = item2.Oid,
                        Ocontent = item2.Ocontent,
                        OisRight = item2.OisRight,
                        Oqid = item2.Oqid,
                    });
                }
                questionRes.Add(new QuestionRes
                {
                    Qid = question.Qid,
                    Qanalysi = question.Qanalysi,
                    Qanswer = question.Qanswer,
                    Qcontent = question.Qcontent,
                    Qexplain = question.Qexplain,
                    QisCheck = question.QisCheck,
                    Qlable = question.Qlable,
                    Qlv = question.Qlv,
                    Qtype = question.Qtype,
                    opiton = optionRes,
                });

            }
            return GetResult(1, "所有题目", questionRes);
        }
        /// <summary>
        /// 结束刷题
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> EndExercisServer(ExerciseDto dto)
        {

            var exe = await _exerciseIOC._examExerciseEFCore.QueryAll(d => d.Euid == dto.EUid).FirstOrDefaultAsync();
            var tast = await _exerciseIOC._examTaskDetailEFCore.QueryAll(d => d.Tduid == dto.EUid).ToListAsync();
            List<ExamTaskDetailProcess> examTaskDetailProcess = new List<ExamTaskDetailProcess>();
            foreach (var item2 in tast)
            {
                examTaskDetailProcess.Add(new ExamTaskDetailProcess
                {
                    Tdpid = Config.GUID(),
                    Tdpedid = exe.Eid,
                    Tdptdid = item2.Tdid,
                    TdpcreateTime = DateTime.Now,
                });
            }
            _exerciseIOC._examTaskDetailProcessEFCore.AddRange(examTaskDetailProcess);
            _exerciseIOC._examTaskDetailProcessEFCore.SaveChanges();
            var taskdetali = await _exerciseIOC._examTaskDetailEFCore.QueryAll(d => d.Tduid.Contains(dto.EUid)).ToListAsync();
            var tasks = await _exerciseIOC._examTaskEFCore.QueryAll(d => 1 == 1).ToListAsync();
            foreach (var item in taskdetali)
            {
                var task = tasks.Where(d => d.Tid == item.Tdtid).FirstOrDefault();
                if (task.TbeginTime < DateTime.Now && task.TendTime > DateTime.Now)
                {
                    if (item.TdbeginTime != null && item.TdisComplete == 0)
                    {
                        item.TdendTime = DateTime.Now;
                    }
                }
            }
            _exerciseIOC._examTaskDetailEFCore.UpdateRange(taskdetali);
            _exerciseIOC._examTaskDetailEFCore.SaveChanges();
            var exercise = await _exerciseIOC._examExerciseEFCore.QueryAll(d => d.Euid == dto.EUid).FirstOrDefaultAsync();
            ExamExercise examExercise = new ExamExercise();
            List<ExamExerciseDetail> examExerciseDetail = new List<ExamExerciseDetail>();
            foreach (var item in dto.exercisdetali)
            {
                examExerciseDetail.Add(new ExamExerciseDetail
                {
                    Edid = Config.GUID(),
                    Edqid = item.EQID,
                    Edoid = item.EOID,
                    Eduid = dto.EUid,
                    EdcreateTime = DateTime.Now,
                });
            }
            if (exercise == null)
            {
                examExercise.Eid = Config.GUID();
                examExercise.Euid = dto.EUid;
                examExercise.Edesc = "";
                examExercise.Etimestamp = dto.ETime;
                examExercise.Ecount = dto.ECount;
                examExercise.EcreateTime = DateTime.Now;
                examExercise.ErightCount = dto.RightCount;
                _exerciseIOC._examExerciseEFCore.Add(examExercise);
                _exerciseIOC._examExerciseDetaliEFCore.AddRange(examExerciseDetail);
                var result = _exerciseIOC._examExerciseEFCore.Transactions(_exerciseIOC._examExerciseEFCore, _exerciseIOC._examExerciseDetaliEFCore);
                return GetResult(result == true ? 1 : 0, result == true ? "添加成功" : "添加失败");
            }
            else
            {
                exercise.Ecount = exercise.Ecount + dto.ECount;
                exercise.ErightCount = exercise.ErightCount + dto.RightCount;
                exercise.Etimestamp = exercise.Etimestamp + dto.ETime;
                _exerciseIOC._examExerciseEFCore.Update(exercise);
                var result = _exerciseIOC._examExerciseEFCore.SaveChanges();
                _exerciseIOC._examExerciseDetaliEFCore.AddRange(examExerciseDetail);
                _exerciseIOC._examExerciseDetaliEFCore.SaveChanges();
                return GetResult(result > 0 ? 1 : 0, result > 0 ? "修改成功" : "修改失败");
            }
        }
        /// <summary>
        /// 获取任务
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetTask(string? uid)
        {
            var tastdetaliser = await _exerciseIOC._examTaskDetailEFCore.QueryAll(d => d.TdisComplete == 1).ToListAsync();//获取完成任务
            var tastdetalis = await _exerciseIOC._examTaskDetailEFCore.QueryAll(d => d.Tduid == uid && d.TdisComplete == 0).ToListAsync();//获取到用户的任务详情
            var tdids = tastdetalis.Select(d => d.Tdid).ToList();//获取任务详情ID
            var tids = tastdetalis.Select(d => d.Tdtid).ToList();//获取任务ID
            var tast = await _exerciseIOC._examTaskEFCore.QueryAll(d => tids.Contains(d.Tid)).ToListAsync();//获取当前用户任务列表
            var tastdetaliprocess = await _exerciseIOC._examTaskDetailProcessEFCore.QueryAll(d => tdids.Contains(d.Tdptdid)).ToListAsync();//获取当前用户任务进度表
                                                                                                                                           //通过任务进度表获取刷题ID
            var eids = tastdetaliprocess.Select(d => d.Tdpedid).ToList();//获取刷题ID
                                                                         //通过刷题ID获取到刷题表
            var exercises = await _exerciseIOC._examExerciseEFCore.QueryAll(d => d.Euid == uid && eids.Contains(d.Eid)).FirstOrDefaultAsync();//获取当前用户刷题数据
            var exercisesdetalis = await _exerciseIOC._examExerciseDetaliEFCore.QueryAll(d => d.Eduid.Contains(uid)).ToListAsync();//获取用户刷题详情
                                                                                                                                   //保存当前刷题数-正确题数-刷题时长
                                                                                                                                   //获取保存数据减去今天最后一次登录的数据
            List<ExercisTaskRes> exercisTasks = new List<ExercisTaskRes>();

            //获取任务
            foreach (var t in tast)
            {
                List<ExercisTaskProcessRes> exercisProcessTasks = new List<ExercisTaskProcessRes>();
                var tastdetali = tastdetalis.Where(d => d.Tdtid == t.Tid && d.Tduid == uid).FirstOrDefault();//获取单个任务详情
                var tastdetaliproces = tastdetaliprocess.Where(d => d.Tdptdid == tastdetali.Tdid).FirstOrDefault();//获取到单个任务进度
                var exercisesdetali = exercisesdetalis.Where(d => t.TbeginTime < d.EdcreateTime && t.TendTime > d.EdcreateTime).ToList();//获取任务时间段算题题数
                var tastser = tastdetaliser.Where(d => d.Tdtid == t.Tid).ToList();//获取单个任务完成人数
                foreach (var item in tastdetaliprocess)
                {
                    if (tastdetaliproces.Tdpid == item.Tdpid)
                    {
                        exercisProcessTasks.Add(new ExercisTaskProcessRes
                        {
                            tdpercent = ((exercisesdetali.Count() * 100) / (t.Tcount)),
                            accomplishcount = tastser.Count(),
                        });
                    }
                }
                if (tastdetaliproces == null)
                {
                    exercisProcessTasks.Add(new ExercisTaskProcessRes
                    {
                        tdpercent = 0,
                        accomplishcount = 0,
                    });
                }

                exercisTasks.Add(new ExercisTaskRes
                {
                    tid = t.Tid,
                    tcount = t.Tcount,
                    tlabel = t.Tlabels,
                    tmax = t.TmaxLv,
                    tmin = t.TminLv,
                    begintime = t.TbeginTime,
                    endtime = t.TendTime,
                    process = exercisProcessTasks,
                });
            }
            return GetResult(1, "任务列表", exercisTasks);
        }
        /// <summary>
        /// 刷新完成任务
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> RefreshTask(ExerciseDto dto)
        {
            var taskdetali = await _exerciseIOC._examTaskDetailEFCore.QueryAll(d => d.Tduid == dto.EUid && d.Tdtid == dto.Tid).FirstOrDefaultAsync();
            if (dto.TDpercent == 100)
            {
                taskdetali.Tdpercent = dto.TDpercent / 100;
                taskdetali.TdisComplete = 1;
            }
            else
            {
                taskdetali.Tdpercent = dto.TDpercent / 100;
                taskdetali.TdisComplete = 0;
            }
            _exerciseIOC._examTaskDetailEFCore.Update(taskdetali);
            var result = await _exerciseIOC._examTaskDetailEFCore.SaveChangesAsync();
            return GetResult(result > 0 ? 1 : 0, result > 0 ? "更新完成" : "更新失败");
        }
        /// <summary>
        /// 获取试卷
        /// </summary>
        /// <param name="lable"></param>
        /// <param name="number"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetTestpaper(string? label, int? lv)
        {
            var testpapers = await _examIOC._examTestPaperEFCore.QueryAll(d => d.Tplabels.Contains(label) && d.Tplv == lv && d.Tptype == 2 && d.TpisPublish == 1 && d.TpisBan == 0).ToListAsync();//获取模拟试卷
            var tpids = testpapers.Select(d => d.Tpid).ToList();//获取试卷ID
            var testpaperdetalis = await _examIOC._examTestPaperDetailEFCore.QueryAll(d => tpids.Contains(d.Tpdtpid)).ToListAsync();//通过试卷ID获取试卷详情
            var qids = testpaperdetalis.Select(d => d.Tpdqid);//获取试题ID
            var questions = await _examIOC._examQuestionEFCore.QueryAll(d => qids.Contains(d.Qid)).ToListAsync();//获取试题
            var options = await _examIOC._examoptionEFCore.QueryAll(d => qids.Contains(d.Oqid)).ToListAsync();
            List<TestPaperRes> testPaperRes = new List<TestPaperRes>();
            foreach (var item in testpapers)
            {
                var testpaperdetali = testpaperdetalis.Where(d => d.Tpdtpid == item.Tpid).ToList();
                var testpaperdetaliqids = testpaperdetali.Select(d => d.Tpdqid).ToList();
                var question = questions.Where(d => testpaperdetaliqids.Contains(d.Qid));
                List<QuestionRes> questionsRes = new List<QuestionRes>();
                foreach (var item2 in question)
                {
                    var option = options.Where(d => d.Oqid == item2.Qid).ToList();
                    List<OptionRes> optionsRes = new List<OptionRes>();
                    foreach (var item3 in option)
                    {
                        optionsRes.Add(new OptionRes
                        {
                            Oqid = item3.Oqid,
                            Ocontent = item3.Ocontent,
                            Oid = item3.Oid,
                            OisRight = item3.OisRight,
                        });
                    }
                    questionsRes.Add(new QuestionRes
                    {
                        Qid = item2.Qid,
                        Qanalysi = item2.Qanalysi,
                        Qanswer = item2.Qanswer,
                        Qcontent = item2.Qcontent,
                        Qexplain = item2.Qexplain,
                        Qlable = item2.Qlable,
                        Qlv = item2.Qlv,
                        opiton = optionsRes,
                    });
                }
                testPaperRes.Add(new TestPaperRes
                {
                    tpid = item.Tpid,
                    tpcount = item.Tpcount,
                    tpexplain = item.Tpexplain,
                    tplabel = item.Tplabels,
                    tplv = item.Tplv,
                    tpname = item.Tpname,
                    score = item.TptotalScore,
                    passscore = item.TppassScore,
                    question = questionsRes,
                });
            }
            return GetResult(1, "模拟试卷", testPaperRes);
        }
        /// <summary>
        /// 开始模拟
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public async Task<ApiResult> BeginSimulation(string? uid, string? tpid)
        {
            var userexe = await _exerciseIOC._examExerciseEFCore.QueryAll(d => d.Euid == uid).FirstOrDefaultAsync();
            if (userexe == null)
            {
                return GetResult(0, "还没开始刷题，请先去刷题吧");
            }
            var sid = Config.GUID();
            var uaid = Config.GUID();
            ExamSimulation examSimulation = new ExamSimulation();
            examSimulation.Sid = sid;
            examSimulation.Suid = uid;
            examSimulation.Stid = tpid;
            examSimulation.ScreateTime = DateTime.Now;
            examSimulation.SfinishTime = null;
            examSimulation.Sscore = null;
            examSimulation.Sdesc = "";
            ExamUserAnswer examUserAnswer = new ExamUserAnswer();
            examUserAnswer.Uedesc = "";
            examUserAnswer.Uesid = sid;
            examUserAnswer.Ueaid = "";
            examUserAnswer.Uaid = uaid;
            examUserAnswer.UecheckUid = null;
            examUserAnswer.UecreateTime = DateTime.Now;
            examUserAnswer.UefinishTime = null;
            examUserAnswer.Uescore = null;
            examUserAnswer.Uestate = 1;
            examUserAnswer.Ueid = uid;
            examUserAnswer.UeisCheck = null;
            _exerciseIOC._examSimulation.Add(examSimulation);
            _exerciseIOC._examSimulation.SaveChanges();
            _examIOC._examUserAnswerEFCore.Add(examUserAnswer);
            _examIOC._examUserAnswerEFCore.SaveChanges();
            List<ExamUserAnswerDetail> answerDetailsRes = new List<ExamUserAnswerDetail>();
            var testpaper = await _examIOC._examTestPaperDetailEFCore.QueryAll(d => d.Tpdtpid == tpid).ToListAsync();
            foreach (var item in testpaper)
            {
                answerDetailsRes.Add(new ExamUserAnswerDetail
                {
                    Uadqid = item.Tpdqid,
                    Uadid = Config.GUID(),
                    Uaduaid = uaid,
                    Uadanswer = "",
                    UaisRight = null,
                    Uadscore = null,
                    UadcreateTime = DateTime.Now,
                });
            }
            _examIOC._examUserAnswerDetailEFCore.AddRange(answerDetailsRes);
            var result = _examIOC._examUserAnswerDetailEFCore.SaveChanges();
            if (result > 0)
            {
                return GetResult(1, "请开始模拟", sid);
            }
            return GetResult(0, "参数错误");
        }
        /// <summary>
        /// 获取试题
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetQuestionSimulation(string? tpid)
        {
            var testpaper = await _examIOC._examTestPaperDetailEFCore.QueryAll(d => d.Tpdtpid == tpid).ToListAsync();
            var testpapers = await _examIOC._examTestPaperEFCore.QueryAll(d => d.Tpid == tpid).FirstOrDefaultAsync();
            testpapers.TpuseCount = testpapers.TpuseCount + 1;
            _examIOC._examTestPaperEFCore.Update(testpapers);
            _examIOC._examTestPaperEFCore.SaveChanges();
            var questions = await _examIOC._examQuestionEFCore.QueryAll(d => 1 == 1).ToListAsync();
            var options = await _examIOC._examoptionEFCore.QueryAll(d => 1 == 1).ToListAsync();
            List<QuestionRes> questionRes = new List<QuestionRes>();
            foreach (var item in testpaper)
            {
                var question = questions.Where(d => d.Qid == item.Tpdqid).Single();
                var option = options.Where(d => d.Oqid == item.Tpdqid).ToList();
                List<OptionRes> optionRes = new List<OptionRes>();
                foreach (var item2 in option)
                {
                    optionRes.Add(new OptionRes
                    {
                        Ocontent = item2.Ocontent,
                        OisRight = item2.OisRight,
                        Oid = item2.Oid,
                        Oqid = item2.Oqid,
                    });
                }
                questionRes.Add(new QuestionRes
                {
                    Qid = question.Qid,
                    Qanalysi = question.Qanalysi,
                    Qanswer = question.Qanswer,
                    Qcontent = question.Qcontent,
                    Qexplain = question.Qexplain,
                    Qlable = question.Qlable,
                    Qlv = question.Qlv,
                    Qtype = question.Qtype,
                    opiton = optionRes,
                });
            }
            return GetResult(1, "生成模拟试题", questionRes);
        }
        /// <summary>
        /// 结束模拟
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public async Task<ApiResult> EndSimulation(SimulationDto dto)
        {
            List<ExamExerciseDetail> examExerciseDetails = new List<ExamExerciseDetail>();
            foreach (var item in dto.option)
            {
                examExerciseDetails.Add(new ExamExerciseDetail
                {
                    Edid = Config.GUID(),
                    EdcreateTime = DateTime.Now,
                    Edqid = item.qid,
                    Eduid = dto.uid,
                    Edoid = item.oid,
                });
            }
            _exerciseIOC._examExerciseDetaliEFCore.AddRange(examExerciseDetails);
            _exerciseIOC._examExerciseDetaliEFCore.SaveChanges();
            float? zong = 0;
            var simulation = await _exerciseIOC._examSimulation.QueryAll(d => d.Sid == dto.sid && d.Suid == dto.uid).SingleAsync();//获取单个模拟
            var answer = await _examIOC._examUserAnswerEFCore.QueryAll(d => d.Uesid == dto.sid && d.Ueid == dto.uid && d.UefinishTime == null).FirstOrDefaultAsync();//获取单个答题卡
            if (answer == null)
            {
                return GetResult(0, "没有需要修改的答题卡");
            }
            var testpage = await _examIOC._examTestPaperDetailEFCore.QueryAll(d => d.Tpdtpid == simulation.Stid).ToListAsync();//获取试卷详情
            var qids = testpage.Select(d => d.Tpdqid).ToList();//获取试题ID
            var questions = await _examIOC._examQuestionEFCore.QueryAll(d => qids.Contains(d.Qid)).ToListAsync();//判断试题是否未主观
            answer.UefinishTime = DateTime.Now;//修改交卷时间
            answer.Uesid = dto.sid;
            simulation.SfinishTime = DateTime.Now;
            var consume = DateTime.Now - answer.UecreateTime;
            var answerdetali = await _examIOC._examUserAnswerDetailEFCore.QueryAll(d => d.Uaduaid == answer.Uaid).ToListAsync();//通过答题卡ID获取答题详情
            var testpages = await _examIOC._examTestPaperDetailEFCore.QueryAll(d => 1 == 1).ToListAsync();//获取试卷详情
            var options = await _examIOC._examoptionEFCore.QueryAll(d => 1 == 1).ToListAsync();//获取选项

            foreach (var item in dto.option)
            {
                var question = questions.Where(d => d.Qid == item.qid).FirstOrDefault();
                if (question.QisCheck == 0)
                {
                    //不是主观
                    var answerqids = answerdetali.Where(d => d.Uadqid == item.qid).FirstOrDefault();//通过答题卡详情获取单个试题
                    var answertestpage = testpages.Where(d => d.Tpdqid == answerqids.Uadqid).FirstOrDefault();
                    var option = options.Where(d => d.Oqid == answerqids.Uadqid).ToList();//通过试题ID获取对应的选项s
                    for (int i = 0; i < option.Count(); i++)
                    {
                        if (option[i].OisRight == 1)
                        {
                            //正确答案
                            if (item.answer == i + 1)
                            {
                                //回答正确
                                answerqids.UaisRight = 1;
                                answerqids.Uadanswer = item.answer.ToString();
                                answerqids.Uadscore = answertestpage.Tpdscore;
                                zong += answertestpage.Tpdscore;
                            }
                            else
                            {
                                //回答错误
                                answerqids.UaisRight = 0;
                                answerqids.Uadscore = 0;
                                answerqids.Uadanswer = item.answer.ToString();
                            }
                        }
                        else
                        {
                            //错误答案
                            if (item.answer == i + 1)
                            {
                                //回答错误
                                answerqids.UaisRight = 0;
                                answerqids.Uadscore = 0;
                                answerqids.Uadanswer = item.answer.ToString();
                            }
                        }
                    }
                }
                else
                {
                    //是主观
                    var answerqids = answerdetali.Where(d => d.Uadqid == item.qid).FirstOrDefault();//通过答题卡详情获取单个试题
                    answerqids.Uadanswer = item.answers;
                }
            }
            _examIOC._examUserAnswerDetailEFCore.UpdateRange(answerdetali);//修改答题卡详情
            _examIOC._examUserAnswerDetailEFCore.SaveChanges();
            answer.Uescore = zong;//统计总分
            simulation.Sscore = zong;
            _exerciseIOC._examSimulation.Update(simulation);
            _exerciseIOC._examSimulation.SaveChanges();
            _examIOC._examUserAnswerEFCore.Update(answer);//修改答题卡
            _examIOC._examUserAnswerEFCore.SaveChanges();
            var result = _examIOC._examQuestionBankEFCore.Transactions(_examIOC._examUserAnswerEFCore, _examIOC._examUserAnswerDetailEFCore);
            var answers = dto.option.Select(d => d.answers).First();
            if (answers == null)
            {
                if (result == true)
                {
                    return GetResult(1, "交卷成功", data: (new
                    {
                        score = zong,
                        consume = consume
                    }));
                }
            }
            return GetResult(0, "交卷成功,包含客观题请次日观看成绩", consume);
        }
        /// <summary>
        /// 获取以模拟试卷
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetSimulationTestPaper(string? uid)
        {
            var simulation = await _exerciseIOC._examSimulation.QueryAll(d => d.Suid == uid).ToListAsync();//获取所有模拟
            var testpapers = await _examIOC._examTestPaperEFCore.QueryAll(d => d.Tptype == 2).ToListAsync();
            List<SimulationRes> simulationRes = new List<SimulationRes>();
            foreach (var item in simulation)
            {
                var testpaper = testpapers.Where(d => d.Tpid == item.Stid).FirstOrDefault();
                if (testpaper != null)
                {
                    simulationRes.Add(new SimulationRes
                    {
                        sid = item.Sid,
                        sscore = item.Sscore,
                        stid = item.Stid,
                        suid = item.Suid,
                        begintime = item.ScreateTime,
                        endtime = item.SfinishTime,
                        score = testpaper.TptotalScore,
                        passscore = testpaper.TppassScore,
                        tpcount = testpaper.Tpcount,
                        tpexplain = testpaper.Tpexplain,
                        tplabel = testpaper.Tplabels,
                        tplv = testpaper.Tplv,
                        tpname = testpaper.Tpname,
                    });
                }
            }
            return GetResult(1, "以模拟试卷", simulationRes);
        }
        /// <summary>
        /// 模拟详情
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="tpid"></param>
        /// <returns></returns>
        public async Task<ApiResult> SimulationParticulars(string? uid, string? tpid, string? sid)
        {
            var simulation = await _exerciseIOC._examSimulation.QueryAll(d => d.Sid == sid && d.Stid == tpid && d.Suid == uid).FirstOrDefaultAsync();
            if (simulation == null)
            {
                return GetResult(0, "未找到该模拟");
            }
            var answer = await _examIOC._examUserAnswerEFCore.QueryAll(d => d.Uesid == simulation.Sid && d.Ueid == uid).FirstOrDefaultAsync();
            var answerdetalis = await _examIOC._examUserAnswerDetailEFCore.QueryAll(d => d.Uaduaid == answer.Uaid).ToListAsync();
            var qids = answerdetalis.Select(d => d.Uadqid).ToList();
            var quesions = await _examIOC._examQuestionEFCore.QueryAll(d => qids.Contains(d.Qid)).ToListAsync();
            var options = await _examIOC._examoptionEFCore.QueryAll(d => qids.Contains(d.Oqid)).ToListAsync();
            List<AnswerDetailsRes> answerDetailsRes = new List<AnswerDetailsRes>();
            foreach (var item3 in answerdetalis)
            {
                var question = quesions.Where(d => d.Qid == item3.Uadqid);
                List<QuestionRes> questionRes = new List<QuestionRes>();
                foreach (var item2 in question)
                {
                    List<OptionRes> optionRes = new List<OptionRes>();
                    var option = options.Where(d => d.Oqid == item2.Qid).ToList();
                    foreach (var item in option)
                    {
                        optionRes.Add(new OptionRes
                        {
                            Ocontent = item.Ocontent,
                            Oid = item.Oid,
                            OisRight = item.OisRight,
                            Oqid = item.Oqid
                        });
                    }
                    questionRes.Add(new QuestionRes
                    {
                        Qid = item2.Qid,
                        Qcontent = item2.Qcontent,
                        Qexplain = item2.Qexplain,
                        Qanswer = item2.Qanswer,
                        Qanalysi = item2.Qanalysi,
                        Qlable = item2.Qlable,
                        Qlv = item2.Qlv,
                        opiton = optionRes
                    });

                    answerDetailsRes.Add(new AnswerDetailsRes
                    {
                        qid = item2.Qid,
                        zscore = simulation.Sscore,
                        answer = item3.Uadanswer,
                        isrtight = item3.UaisRight,
                        score = item3.Uadscore,
                        question = questionRes
                    });
                }
            }
            return GetResult(1, "模拟详情", answerDetailsRes);
        }
        /// <summary>
        /// 刷题数量排名
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public async Task<ApiResult> ExerciseCountRanking(string? uid, string? token)
        {
            var exercise = await _exerciseIOC._examExerciseEFCore.QueryAll(d => d.Ecount, false).ToListAsync();
            var uids = exercise.Select(d => d.Euid).ToList();
            var exercisedetalis = await _exerciseIOC._examExerciseDetaliEFCore.QueryAll(d => 1 == 1).ToListAsync();
            var useexercise = await _exerciseIOC._examExerciseEFCore.QueryAll(d => d.Euid == uid).FirstOrDefaultAsync();
            List<ExercisChlirenRes> exercisChlirenRes = new List<ExercisChlirenRes>();
            ExercisRes exercisRes = new ExercisRes();
            foreach (var item in exercise)
            {
                if (item.Euid == useexercise.Euid)
                {
                    exercisRes.ranking = exercise.IndexOf(item) + 1;
                }
                var exercisedetali = exercisedetalis.Where(d => d.Eduid == item.Euid).ToList();
                double? count = exercisedetali.Count();
                double? sum = item.ErightCount;
                exercisChlirenRes.Add(new ExercisChlirenRes
                {
                    Ouid = item.Euid,
                    Ocount = item.Ecount,
                    Ouname = GetUser(item.Euid, token),
                });
            }
            var usercount = exercisedetalis.Where(d => d.Eduid == uid).ToList();

            exercisRes.uid = uid;
            exercisRes.uname = GetUser(useexercise.Euid, token);
            exercisRes.count = useexercise.Ecount;
            exercisRes.chilren = exercisChlirenRes;
            return GetResult(1, "数量排名", exercisRes);
        }
        /// <summary>
        /// 刷题正确率排名
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public async Task<ApiResult> ExerciseAccuracyRanking(string? uid, string? token)
        {
            var exercise = await _exerciseIOC._examExerciseEFCore.QueryAll(d => d.Ecount, false).ToListAsync();
            var uids = exercise.Select(d => d.Euid).ToList();
            var exercisedetalis = await _exerciseIOC._examExerciseDetaliEFCore.QueryAll(d => 1 == 1).ToListAsync();
            var useexercise = await _exerciseIOC._examExerciseEFCore.QueryAll(d => d.Euid == uid).FirstOrDefaultAsync();
            List<ExercisChlirenRes> exercisChlirenRes = new List<ExercisChlirenRes>();
            ExercisRes exercisRes = new ExercisRes();
            foreach (var item in exercise)
            {
                if (item.Euid == useexercise.Euid)
                {
                    exercisRes.ranking = exercise.IndexOf(item) + 1;
                }
                var exercisedetali = exercisedetalis.Where(d => d.Eduid == item.Euid).ToList();
                double? count = exercisedetali.Count();
                double? sum = item.ErightCount;
                exercisChlirenRes.Add(new ExercisChlirenRes
                {
                    Ouid = item.Euid,
                    Oaccuracy = sum / count,
                    Ouname = GetUser(item.Euid, token),
                });
            }
            var usercount = exercisedetalis.Where(d => d.Eduid == uid).ToList();
            exercisRes.uid = uid;
            exercisRes.uname = GetUser(useexercise.Euid, token);
            exercisRes.accuracy = (useexercise.ErightCount / usercount.Count())*100;
            exercisRes.chilren = exercisChlirenRes;
            return GetResult(1, "数量排名", exercisRes);
        }
        /// <summary>
        /// 刷新旧任务
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult> RefreshOldTask()
        {
            var task = await _exerciseIOC._examTaskEFCore.QueryAll(d => d.TbeginTime, false).ToListAsync();
            foreach (var item in task)
            {
                if (item.Tcycle != null && item.TendTime <= DateTime.Now)
                {
                    var time = DateTime.Now.AddDays(Convert.ToInt32(item.Tcycle));
                    item.TbeginTime = DateTime.Now;
                    item.TendTime = time;
                }
            }
            _exerciseIOC._examTaskEFCore.UpdateRange(task);
            var result = _exerciseIOC._examTaskEFCore.SaveChanges();
            return GetResult(1, "任务更新完成");
        }
    }
}
